/**
 * YzmCMS 公共js文件 (yzm cms轻量级开源CMS)
 * 
 * @author           袁志蒙  
 * @license          http://www.yzmcms.com
 * @lastmodify       2020-05-12
 */

 
//删除一条记录
function yzm_del(url){
	var is_ajax = arguments[1] || 0;
	var symbol = url.indexOf('?')<0 ? '?' : '&';
	url += symbol+'yzm_csrf_token='+yzm_csrf_token;
	layer.confirm('确认要删除吗？', {title:"操作提示"}, function(index){
		if(!is_ajax){
			window.location.href = url;
		}else{
			layer.msg('正在操作中……', {icon:16, time:0, shade:0.3});
			$.ajax({
		        type: "GET",
		        url: url, 
			    dataType: "json", 
		        success: function (msg) {
		        	if(msg.status == 1){
		        		layer.msg(msg.message, {icon:1,time:1000},function(){
		        			window.location.reload();
		        		});
		        	}else{
		        		layer.msg(msg.message, {icon:2,time:2500});
		        	}
		        }
		    })
		}
	});
}


//删除多条记录
function yzm_dels(name){
	var is_ajax = arguments[1] || 0;
	if ($("input[name='"+name+"[]']:checked").length<1){
	   layer.alert('请选择要操作的记录！', {title:"操作提示"});
	   return false;
	}	
	layer.confirm('确认要删除吗？', {title:"操作提示"}, function(index){
		if(!is_ajax){
			$("#myform").submit();
		}else{
			layer.msg('正在操作中……', {icon:16, time:0, shade:0.3});
			$.ajax({
		        type: "POST",
		        url: $("#myform").attr("action"), 
		        data: $("#myform").serialize(),
			    dataType: "json", 
		        success: function (msg) {
		        	if(msg.status == 1){
		        		layer.msg(msg.message, {icon:1,time:1000},function(){
							window.location.reload();
						});
		        	}else{
		        		layer.msg(msg.message, {icon:2,time:2500});
		        	}
		        }
		    })
		}
	});
}


//确认窗口
function yzm_confirm(url, title, is_ajax, is_filter) {
	if (is_ajax == undefined || is_ajax == null) {
		is_ajax = false;
	}
	if (is_filter == undefined || is_filter == null) {
		is_filter = true;
	}
	var symbol = url.indexOf('?')<0 ? '?' : '&';
	url += symbol+'yzm_csrf_token='+yzm_csrf_token;
	title = is_filter ? yzm_htmlspecialchars(title) : title;
	layer.confirm(title, {title:"操作提示"}, function(index){
		if(!is_ajax){
			window.location.href = url;
		}else{
			layer.msg('正在操作中……', {icon:16, time:0, shade:0.3});
			$.ajax({
		        type: "GET",
		        url: url, 
			    dataType: "json", 
		        success: function (msg) {
		        	if(msg.status == 1){
		        		layer.msg(msg.message, {icon:1,time:1000},function(){
		        			window.location.reload();
		        		});
		        	}else{
		        		layer.msg(msg.message, {icon:2,time:2500});
		        	}
		        }
		    })
		}
	});
}


//打开页面
function yzm_open(title,url,w,h){
	if (w == undefined || w == null) {
		w = ($(window).width() * 0.8);
	}
	if (h == undefined || h == null) {
		h = ($(window).height() * 0.8);
	}
	layer.open({
		type: 2,
		area: [w+'px', h +'px'],
		fix: false, 
		// maxmin: true,
		shade:0.4,
		title: yzm_htmlspecialchars(title),
		content: url
	});
	return false;
} 

 
//大窗口打开页面
function yzm_open_full(title,url){
	var index = layer.open({
		type: 2,
		title: yzm_htmlspecialchars(title),
		content: url
	});
	layer.full(index);
}


//关闭弹出层
function yzmcms_close(){
	var index = parent.layer.getFrameIndex(window.name);
	parent.layer.close(index);
}


//上传附件
function yzm_upload_att(url){
	layer.open({
      type: 2,
      title: '上传附件',
      area: ['500px', '430px'],
      content: url
    });
}


//图像裁剪
function yzm_img_cropper(cid, url){
	var str = $('#' + cid).val();
	if(str == ''){
		layer.msg('请先上传图片！', {icon:2,time:2500});
		return false;
	}
	if(url.indexOf('?') != -1) {
		url = url+'&f=' + window.btoa(unescape(encodeURIComponent(str))) + '&cid='  + cid;
	} else {
		url = url+'?f=' + window.btoa(unescape(encodeURIComponent(str))) + '&cid='  + cid;
	}
	layer.open({
      type: 2,
      title: '图像裁剪',
      area: ['770px', '510px'],
      content: url
    });
}


//图片预览(根据id)
function yzm_img_preview(id, src){
	if(src == '') return;
	var ext = src.substr(src.lastIndexOf(".")+1);
	if(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico'].indexOf(ext.toLowerCase()) === -1) return;
	layer.tips('<img src="'+yzm_htmlspecialchars(src)+'" style="max-width:180px;max-height:250px" >', '#'+id, {
	  tips: [1, '#fff']
	});	
}


//图片预览(根据对象)
function yzm_img_browse(obj, src){
	if(src == '') return;
	var ext = src.substr(src.lastIndexOf(".")+1);
	if(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico'].indexOf(ext.toLowerCase()) === -1) return;
	layer.tips('<img src="'+yzm_htmlspecialchars(src)+'" style="max-width:180px;max-height:250px">', obj, {
	  tips: [1, '#fff']
	});	
}


//添加远程地址
function yzm_add_attachment(id){
	var string = '<li>文件：<input type="text" name="'+id+'[url][]" value="" onmouseover="yzm_img_browse(this, this.value)" onmouseout="layer.closeAll(\'tips\')" class="input-text yzm-input-url"> 描述：<input type="text" name="'+id+'[alt][]" value="" class="input-text yzm-input-alt"><a href="javascript:;" class="secondary" onclick="yzm_move_li(this, 1);">上移</a> <a href="javascript:;" class="secondary" onclick="yzm_move_li(this, 0);">下移</a> <a href="javascript:;" class="danger" onclick="yzm_delete_li(this);">删除</a></li>';
	
	$("#"+id).append(string);	
}


//删除多文件
function yzm_delete_li(obj){
	 $(obj).parent().remove();
}


//多文件上下移动
function yzm_move_li(obj, is_up) {
	if(is_up){
		var prevLi = $(obj).parent("li").prev();
		if(prevLi.length){
		    prevLi.before($(obj).parent("li"));
		}
	}else{
	    var nextLi = $(obj).parent("li").next();
	    if(nextLi.length){
	        nextLi.after($(obj).parent("li"));
	    }
	}
}


//html实体转换
function yzm_htmlspecialchars(str)  {  
    str = str.replace(/&/g, '&amp;');
    str = str.replace(/</g, '&lt;');
    str = str.replace(/>/g, '&gt;');
    str = str.replace(/"/g, '&quot;');
    str = str.replace(/'/g, '&#039;');
    return str;
}


//新窗口打开
function yzm_win_open(url,name,w,h) {
	if (w == undefined || w == null) {
		w = screen.width;
	}
	if (h == undefined || h == null) {
		h = screen.height;
	}
	var winobj = window.open(url,name,"width=" + w + ",height=" + h + ",toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no");
	var loop = setInterval(function(){
		if(winobj.closed){
			clearInterval(loop);
			location.reload();
		}
	},1000);
}


//设置每页展示条数
function yzm_page_size(obj) {
	var url = $(obj).data('url').replace("PAGE", 1);
	if(url.indexOf('page_size')<0){
		var page_size = url.indexOf('page_size')<0 ? (url.indexOf('?')<0 ? '?' : '&')+'page_size='+obj.value : '';
		url = url+page_size;
	}else{
		url = url.replace(/\/page_size\/[0-9]*/i, '/page_size/'+obj.value);
		url = url.replace(/page_size=[0-9]*/i, 'page_size='+obj.value);
	}
	window.location.href = url;
}


//跳转到指定页
function yzm_page_jump(obj) {
	var theEvent = window.event;
	if (theEvent.keyCode != 13)  return true;
	var url = $(obj).data('url');
	var page = $(obj).val();
	if(page == '' || isNaN(page)){
		alert('请输入正确的页码！');
		return false;
	}
	url = url.replace("PAGE", page);
	window.location.href = url;
	return false;
}


//自动提示
function yzm_auto_tips(){
    var html = '<a class="yzm-tips" href="javascript:void(0);" onmouseover="yzm_tips = layer.tips($(this).parent().find(\'span.yzm-explain\').html(), this, {time:100000});" onmouseout="layer.close(yzm_tips);"><i class="yzm-iconfont yzm-iconbangzhu yzm-tips-icon"></i></a>';
    $.each($('.yzm-explain-box > span.yzm-explain'), function(index, item){
        if ($(item).html() != '') {
            $(item).before(html);
        }
    });
}


//状态切换
function yzm_change_status(obj, url) {
	var id = $(obj).data('id');
	var field = $(obj).data('field');
	var value = $(obj).hasClass('yzm-status-disable') ? 1 : 0;
	//自定义状态标签 csw 
	var t = $(obj).hasClass('yzm-status-disable') ? '是' : '否';
	var pre_t = $(obj).hasClass('yzm-status-disable') ? '否' : '是';
	var db = $(obj).data('db') ? $(obj).data('db') : '';
	
	//自定义状态标签 csw 
	if($(obj).data('text')){
		var temp = $(obj).data('text').split('|');
		var t = $(obj).hasClass('yzm-status-disable') ? temp[0] : temp[1];
		var pre_t = $(obj).hasClass('yzm-status-disable') ? temp[1] : temp[0];
	}

	$.ajax({
        type: "POST",
        url: url, 
        data: {"id":id,"field":field,"value":value,"yzm_csrf_token":yzm_csrf_token,db:db},
	    dataType: "json", 
        success: function (msg) {
        	if(msg.status == 1){
        		layer.msg(msg.message, {icon:1,time:800});
        		if(value){
        			$(obj).removeClass('yzm-status-disable').addClass('yzm-status-enable');
        			$(obj).html('<i class="yzm-iconfont">&#xe81f;</i>'+t);
        		}else{
        			$(obj).removeClass('yzm-status-enable').addClass('yzm-status-disable');
        			$(obj).html('<i class="yzm-iconfont">&#xe601;</i>'+t);
        		}
        	}else{
        		layer.msg(msg.message, {icon:2,time:2500});
        	}
        }
    })
}


// 查看大图
function yzm_show_img(src, max_width, max_height) {
	var img = '<img src="' + src + '">';
	$(img).load(function() {
		width  = this.width;
		height = this.height;
		if (this.width > max_width) {
			width = max_width + 'px';
			height = 'auto';
		}
		if (this.height > max_height) {
			width = 'auto';
			height = max_height + 'px';
		}
		var string = '<style type="text/css">.layui-layer-page .layui-layer-content{overflow-y:hidden;}</style><img src="'+src+'" style="width:'+width+';height:'+height+';">';
		layer.open({
			type: 1,
			title: false,
			area: [width, height],
			content: string,
			shadeClose: true
		});
	})
}

//layui table 公用方法
function public_table(db){
	$('#btn_del').on('click',function(){
		var tableStatus = table.checkStatus('table');
		if(tableStatus.data.length<1){
			layer.msg('请先选择要删除的数据', {icon:2});
			return false;
		}
		var data={};
		data.db = db;
		data.ids = [];
		tableStatus.data.forEach(obj => {
		  data.ids.push(obj.id);
		});
		layer.confirm('确认要批量删除吗？', {title:"操作提示"}, function(index){
			$.ajax({
				type: 'POST',
				url: 'public_del', 
				dataType: "json", 
				data:data,
				success: function (res) {
					if(res.status == 1){
						layer.msg(res.message, {icon:1,time:800});
                        //layui中找到CheckBox所在的行，并遍历找到行的顺序
                        $('div.layui-table-body table tbody input[name="layTableCheckbox"]:checked').each(function () { // 遍历选中的checkbox
                            n = $(this).parents('tbody tr').index()  // 获取checkbox所在行的顺序
                            //移除行
                            $('div.layui-table-body table tbody ').find('tr:eq(' + n + ')').remove()
                            //如果是全选移除，就将全选CheckBox还原为未选中状态
                            $('div.layui-table-header table thead div.layui-unselect.layui-form-checkbox').removeClass('layui-form-checked')
                        })
						//table.reload('table',{where:$('#search').serializeJson()});
					}else{
						layer.msg(res.message, {icon:2});
					}
				}
			})
		})
	})
	$('.btn_action').on('click',function(){
		var tableStatus = table.checkStatus('table');
		var data=$('#search').serializeJson();
		data.db = db;
		data.ids = [];
		tableStatus.data.forEach(obj => {
		  data.ids.push(obj.id);
		});
		var txt = $(this).text();
		var tip = '按搜索条件'+txt+'？'+$('.layui-laypage-count').html();
		if(data.ids.length>0){
			tip = '勾选的'+txt+'？';
		}
		var url = $(this).attr('action_url');
		layer.confirm(tip, {title:"操作提示"}, function(index){
			var index = layer.load(1);
			$.ajax({
				type: 'POST',
				url: url, 
				dataType: "json", 
				data:data,
				success: function (res) {
					layer.close(index);
					if(res.code == 0){
						layer.msg(res.msg, {icon:1, time:800}, function(){
							table.reload('table',{where:$('#search').serializeJson()});
						});
					}else{
						layer.msg(res.msg, {icon:2});
					}
				}
			})
		})
	})
}

function init_table(db){
	
	//小屏幕时隐藏操作列
	if($(window).width()<1000){
		table.hideCol('table', {field: 'toolbar',hide: true});
	}
	
	//监听操作按钮
	table.on('tool(table)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
		var data = obj.data //获得当前行数据
		,layEvent = obj.event; //获得 lay-event 对应的值
		if(layEvent === 'delete'){
			layer.confirm('确定删除该行数据？', function(index){
				//回车即保存
				var data = {};
				data.ids
				data.db = db;
				data.ids = [obj.data.id];
				$.ajax({
					type: 'POST',
					url: 'public_del', 
					dataType: "json", 
					data:data,
					success: function (res) {
						if(res.status == 1){
							layer.msg(res.message, {icon:1,time:800});
							obj.del(); //删除对应行（tr）的DOM结构
							layer.close(index);
							//向服务端发送删除指令
						}else{
							layer.msg(res.message, {icon:2});
						}
					}
				})
			});
		}
	});
	
	//排序
	table.on('sort(table)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"	  
		//尽管我们的 table 自带排序功能，但并没有请求服务端。
		//有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
		$('input[name="field"]').val(obj.field);
		$('input[name="order"]').val(obj.type);
			table.reload('table', {
			initSort: obj, //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
			where: $('#search').serializeJson()
		});
	});
	
	//搜索按钮
	$('#btn_search').on('click',function(){
		table.reload('table',{where:$('#search').serializeJson()});
	})
	
	//重置按钮
	$('#btn_reset').on('click',function(){
		table.reload('table',{where:$('#search').serializeJson()});
	})
	
	//编辑
	table.on('edit(table)',function (obj) {
		var data = {};
		//回车即保存
		data.db = db;
		data.id = obj.data.id;
		data.field = obj.field;
		data.value = obj.value;
		$.ajax({
			type: 'POST',
			url: 'public_edit_field', 
			dataType: "json", 
			data:data,
			success: function (res) {
				if(res.status == 1){
					layer.msg(res.message, {icon:1,time:800}); 
				}else{
					layer.msg(res.message, {icon:2});
				}
			}
		})
	})
}
function getRowData(tableId, elem){
	var index = $(elem).closest('tr').data('index');
	return table.cache[tableId][index] || {};
};

function select_table(options,setting,elem,db,field){
	dropdown.render({
		elem: elem,
		// trigger: 'hover',
		// 此处的 data 值，可根据 done 返回的 res 遍历来赋值
		data: setting,
		click: function(obj){
			var data = getRowData(options.id, this.elem); // 获取当前行数据(如 id 等字段，以作为数据修改的索引)
			var data_post = {};
			data_post.id = data.id;
			data_post.db = db;
			data_post.field = field;
			data_post.value = obj.id;
			var that =this;
			$.ajax({
				type: 'POST',
				url: 'public_edit_field', 
				dataType: "json", 
				data:data_post,
				success: function (res) {
					if(res.status == 1){
						data.platform = obj.title;
						that.elem.find('span').html(obj.title);
						layer.msg(res.message, {icon:1,time:800}); 
					}else{
						layer.msg(res.message, {icon:2});
					}
				}
			})
		}
	});
}

//点击导出新窗口打开
function download_file(url) {
    var a = document.createElement('a');
    a.setAttribute('href', url);
    a.setAttribute('target', '_blank');
    var id = Math.random(10000, 99999);
    a.setAttribute('id', id);
    // 防止反复添加
    if (!document.getElementById(id)) {
        document.body.appendChild(a);
    }
    a.click();
}

//esc退出弹窗
$(document).on('keydown', function(event){
	if(event.keyCode === 27){ // 27 是 Esc 键的键码
	  layer.closeAll(); // 关闭所有弹层
	}
});

$('.list_box').on('mouseover',function(){
	$(this).find('.select').show();
})

$('.list_box').on('mouseout',function(){
	$(this).find('.select').hide();
})

$('.list_box li input').click(function(){
	let brand = [];
	$(this).parents('ul').find('input').each(function(){
		let obj = $(this); 
		if(obj.is(':checked')){
			brand.push(obj.attr('data'));
		}
	})
	$(this).parents('.select').prev().val(brand.join(','));
})

function download(data,url,obj){
	$.ajax({  
		url: url,
		type: 'POST',
		data: data,
		dataType: "json",
		success: function (res) {
			if(res.code == 1){
				layer.msg(res.msg, {icon:2,time:2500});
				return false;
			}
			if(res.code == 2){
				console.log(res.msg);
				download(data,url,obj);
			}
			if(res.code == 0){
				obj.find('.yzm-iconxiazai').html(' 导出');
				$('input[name="download"]').val(0);
				obj.toggleClass('btn-warning');
				// 创建一个临时的 URL  
				var url = res.url; 
				// 创建一个 a 标签用于下载  
				var a = document.createElement('a');  
				a.href = url;
				// 将 a 标签添加到文档中（可选，但有助于在某些浏览器中触发下载）  
				document.body.appendChild(a);  
				// 触发下载  
				a.click();  
				// 清理：从文档中移除 a 标签，并释放 URL 对象  
				document.body.removeChild(a);  
				window.URL.revokeObjectURL(url);
			}
		},  
		error: function(xhr, status, error) {  
			// 处理错误  
			console.error('Error downloading file:', error);
			obj.find('.yzm-iconxiazai').html(' 导出');
			$('input[name="download"]').val(0);
			obj.toggleClass('btn-warning');
		} 
	});
}




$('#btn_download').click(function(){
	var url = $(this).attr('url');
	$('input[name="download"]').val(1);
	var data = $('form').serializeArray();
	var _this = $(this);
	if(!_this.hasClass('btn-warning')){
		layer.msg('导出中...', {icon:2,time:2500});
		return false;
	}
	$(this).find('.yzm-iconxiazai').html(' 导出中...');
	$(this).toggleClass('btn-warning');
	// 假设这是你的 AJAX 请求  
	download(data,url,_this);
})

$(function(){
	$('input').keydown(function(e) {
		var name = $(this).attr('name');
		if (e.which == 13) { // 检查按键是否是Enter
			if($('input[name="'+name+'"]').val()!=''){
				return table.reload('table',{where:$('#search').serializeJson()});
			}
			$('#'+name+' .textarea').val('');
			if(name!='sku_id'&&name!='i_id'&&name!='other_2'&&name!='po_id'){
				return false;
			}
			// 在这里编写按下Enter时想要执行的代码
			layer.open({
			  type: 1,
			  title: '批量输入',
			  shadeClose: true,
			  shade: 0.8,
			  maxmin: true, //开启最大化最小化按钮
			  area: ['600px', '300px'],
			  content: $('#'+name)
			});
		}
	});
	$(document).keydown(function(event) {  
		// 检查是否按下了Esc键  
		if (event.key === "Escape") {
			layer.closeAll();
		}  
	});  
})
function submit_input(id){
	var val = $('#'+id+' .textarea').val();
	var val = val.replace(/，/g, ",");
	if(val.indexOf(",") > -1){
		var lines = val.split(','); // 使用换行符分割字符串
		var vals = [];
		$.each(lines, function(index, value) {
			if($.trim(value)!=''){
				vals.push($.trim(value));
			}
		});
	}else{
		var lines = val.split('\n'); // 使用换行符分割字符串
		var vals = [];
		$.each(lines, function(index, value) {
			if($.trim(value)!=''){
				vals.push($.trim(value));
			}
		});
	}
	if(vals.length>5000){
		layer.msg('单次最多查询5000个', {icon:2,time:2500});
		return false;
	}
	$('input[name="'+id+'"]').val(vals.join(','));
	layer.closeAll();
}
